package com.leshua.channel.mpos.filter;

import com.leshua.channel.mpos.common.BodyReaderHttpServletRequestWrapper;
import com.leshua.channel.mpos.common.utils.LoggerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * 通用过滤器，做请求和返回的日志处理
 */
@Component
@WebFilter(filterName = "commonFilter", urlPatterns = "/api/*")
@Order(1)
public class CommonFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CommonFilter.class.getSimpleName());

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
    	HttpServletRequest req = (HttpServletRequest) servletRequest;  
        long startTimeMillions = System.currentTimeMillis();

        ServletRequest requestWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {
            requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        }
        if (null == requestWrapper) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
            chain.doFilter(requestWrapper, servletResponse);
        }

        long endTimeMillions = System.currentTimeMillis();
        LoggerUtil.summary(req.getRequestURI(),	endTimeMillions - startTimeMillions);
    }

    @Override
    public void destroy() {

    }
}